import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {getQueryString} from '../utils/util';
import { Flex,PullToRefresh, ListView, SearchBar, NavBar, Icon, List, Carousel, Tabs} from 'antd-mobile';

import 'antd-mobile/lib/flex/style/index.css';
import 'antd-mobile/lib/search-bar/style/index.css';
import 'antd-mobile/lib/pull-to-refresh/style/index.css';
import 'antd-mobile/lib/list-view/style/index.css';
import 'antd-mobile/lib/nav-bar/style/index.css';
import 'antd-mobile/lib/icon/style/index.css';
import 'antd-mobile/lib/list/style/index.css';
import 'antd-mobile/lib/drawer/style/index.css';
import 'antd-mobile/lib/carousel/style/index.css';
import 'antd-mobile/lib/tabs/style/index.css';
import '../static/styles/activity.css';

import ActivityItem from '../components/activityItem';
import Footer from '../components/footer';

import loadIcon from '../static/icon/load.gif';

import { get } from '../api/getData';

let pageIndex = 1;
let index = 0;

let initListViewSize = 20;

function genData(obj, refreshing=false, isLoading=false, pIndex = 1) {
    let reqParams = {
        page:pIndex,
        length:20,
        ...obj.state.search
    };

    get('/api/activity/list', reqParams, function (error, data) {
        if(null === error){
            console.log(data.data.length);
            if(data.code === 0){
                if(pIndex > 1){
                    obj.rData = [...obj.rData, ...data.data.list];
                    obj.setState({
                        data : obj.state.data.concat(data.data.list)
                    });
                }else {
                    obj.rData = data.data.list;
                    obj.setState({
                        data : data.data.list
                    });
                    ReactDOM.findDOMNode(obj.lv).scrollTop = 0;
                }

                if(data.data.list.length === 0){
                    obj.setState({
                        hasMore : false
                    })
                }

                obj.setState({
                    dataSource: obj.state.dataSource.cloneWithRows(obj.rData),
                    refreshing: refreshing,
                    isLoading: !isLoading
                });
            }
        }
    });
}

class Index extends Component {
    constructor(props) {
        super(props);
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });

        this.rData = [];

        let searchKey = getQueryString('searchKey');

        let searchStyle = {
            right:'28px',
            background:'none',
            position: 'absolute',
            top: '0',
            width: '80%'
        };

        this.state = {
            dataSource,
            refreshing: true,
            isLoading: true,
            height: document.documentElement.clientHeight,
            useBodyScroll: false,
            data : [],
            searchStyle : searchStyle,
            open : false,
            search:{cid:getQueryString('cid'),searchKey:searchKey},
            category:[],
            hasMore:true,
            searchKey : searchKey?searchKey:'',
            banner:[],
            imgHeight:180
        };


    }

    componentDidUpdate() {
        if (this.state.useBodyScroll) {
            document.body.style.overflow = 'auto';
        } else {
            document.body.style.overflow = 'hidden';
        }
    }

    componentWillMount(){
        let __this = this;
        get('/api/activity/banner', {} , function(error, data){
            if(null === error){
                if(data.code === 0){
                    __this.setState({
                        banner: data.data.list
                    });
                }
            }
        });
        get('/api/activity/classify', {}, function (error, data) {
            if(null === error){
                if(data.error === undefined){
                    __this.setState({
                        category: data.data
                    });
                }
            }
        });

        let token = getQueryString('token');
        window.sessionStorage.setItem('youji-token', token);
    }

    componentWillUnmount(){
        window.sessionStorage.setItem('list-cache', JSON.stringify(this.state));
    }

    componentDidMount() {
        if(window.sessionStorage.getItem('list-cache') !== null) {
            let stateData = JSON.parse((window.sessionStorage.getItem('list-cache')));
            this.rData = stateData.data;
            initListViewSize = stateData.data.length;
            this.setState({
                dataSource : this.state.dataSource.cloneWithRows(stateData.data),
                refreshing: stateData.refreshing,
                isLoading: stateData.isLoading,
                height: stateData.height,
                useBodyScroll: stateData.useBodyScroll,
                data : stateData.data,
                searchStyle : stateData.searchStyle,
                open : stateData.open,
                search:stateData.search,
                category:stateData.category,
                hasMore:stateData.hasMore,
                searchKey : stateData.searchKey?stateData.searchKey:'',
            } , function () {
                let scrollTopValue = window.sessionStorage.getItem('scroll-top-cache') ? window.sessionStorage.getItem('scroll-top-cache') : 0;
                ReactDOM.findDOMNode(this.lv).scrollTop = scrollTopValue;

                window.sessionStorage.removeItem('list-cache');
                window.sessionStorage.removeItem('scroll-top-cache');
            });

        }else {
            const hei = this.state.height - ReactDOM.findDOMNode(this.lv).offsetTop - (this.state.height - ReactDOM.findDOMNode(this.footer).offsetTop);

            this.setState({
                height: hei,
            } , function () {
                genData(this);
            });
        }

        document.title = '游记';
    }

    onScroll(e){
        window.sessionStorage.setItem('scroll-top-cache', e.target.scrollTop);
    }

    onRefresh = () => {
        this.setState({ refreshing: false, isLoading: false } , function () {
            genData(this, false, false);
        });
    };

    onEndReached = (event) => {
        if (this.state.isLoading && !this.state.hasMore) {
            return;
        }
        this.setState({ isLoading: true ,refreshing: false} ,function () {
            genData(this, false, true, ++pageIndex);
        });
    };

    onOpenChange = () => {
        this.setState({ open: !this.state.open });
    };

    showSearch = () => {
        this.manualFocusInst.focus();
        this.setState({
            searchStyle:{
                right:'28px',
                background:'none',
                position: 'absolute',
                top: '0',
                width: '80%'
            }
        });
    };

    hideSearch = () => {
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:null},
            refreshing: false,
            isLoading: true,
            searchKey:'',
            searchStyle:{
                right:'28px',
                background:'none',
                position: 'absolute',
                top: '0',
                width: '80%'
            }
        }, genData.bind(this, this, false, true));
    };

    reqCategory(cid) {
        pageIndex = 1;
        this.setState({
            search : {cid:cid,searchKey:''},
            refreshing: false,
            isLoading: true,
            open:false,
        }, genData.bind(this, this, false, false));
    };

    submitSearch(){
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:this.state.searchKey},
            refreshing: false,
            isLoading: true
        }, genData.bind(this, this, false, true));
    }

    searchValueChange(value){
        this.setState({ searchKey: value});
    }

    searchValueClear(){
        pageIndex = 1;
        this.setState({
            search : {cid:null,searchKey:null},
            refreshing: false,
            isLoading: true,
            searchKey:'',
            searchStyle:{
                right:'-1000px'
            }
        }, genData.bind(this, this, false, true));
    }

    tabChange(tab){
        console.log(tab);
    }

    render() {
        const tabs = [{cid:0,title:'所有活动'}];

        for (var i = 0; i < this.state.category.length; i++) {
            tabs.push({cid:this.state.category[i].id,title:this.state.category[i].classname});
        }

        const row = (rowData, sectionID, rowID) => {
            console.log(rowData);
            if(rowID % 2 !== 0) {
                return (
                    <div className="list-view-item ml10" key={rowID}>
                        <ActivityItem data={rowData}/>
                    </div>
                );
            }else{
                return (
                    <div className="list-view-item " key={rowID}>
                        <ActivityItem  data={rowData}/>
                    </div>
                );
            }


        };

        return (
            <div className='pb120' style={{overflowX:'hidden'}}>
                <div className='banner'>
                    <Carousel
                        autoplay={true}
                        infinite
                      >
                        {this.state.banner.map(val => (
                          <a
                            key={val.img}
                            href={val.redirect_url}
                            style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                          >
                            <img
                              src={val.img}
                              alt={val.title}
                              style={{ width: '100%', verticalAlign: 'top' }}
                              onLoad={() => {
                                // fire window resize event to change height
                                window.dispatchEvent(new Event('resize'));
                                this.setState({ imgHeight: 'auto' });
                              }}
                            />
                            <div className='banner-title'>{val.title}</div>
                          </a>
                        ))}
                      </Carousel>
                    <SearchBar
                        value={this.state.searchKey}
                        placeholder="请输入的您要搜索的内容"
                        style={this.state.searchStyle}
                        maxLength={30}
                        ref={ref => this.manualFocusInst = ref}
                        onCancel={this.hideSearch}
                        onSubmit={this.submitSearch.bind(this)}
                        onChange={this.searchValueChange.bind(this)}
                        onClear={this.searchValueClear.bind(this)}
                    />
                </div>

                <Tabs tabs={tabs}
                      initialPage={0}
                      ref={el => this.lv = el}
                      onChange={(tab, index) => this.reqCategory(tab.cid)}
                      onTabClick={(tab, index) => { console.log('onTabClick', index, tab); }}
                      renderTabBar={props => <Tabs.DefaultTabBar {...props} page={4} />}
                    >
                            <ListView
                                className='activity-list'
                                key={this.state.useBodyScroll ? '0' : '1'}

                                dataSource={this.state.dataSource}
                                renderFooter={() => (<div style={{ textAlign: 'center' }}>
                                    {this.state.isLoading ? '刷新中...' : this.state.hasMore ? '上拉刷新' : '没有更多了'}
                                </div>)}
                                renderRow={row}
                                useBodyScroll={this.state.useBodyScroll}
                                style={this.state.useBodyScroll ? {} : {
                                    height: this.state.height,
                                    textAlign:'center'
                                }}
                                pullToRefresh={<PullToRefresh
                                    refreshing={this.state.refreshing}
                                    onRefresh={this.onRefresh}
                                    indicator={{activate : <div className="list-view-indicator"><img src={loadIcon} alt=""/></div>, deactivate : <div className="list-view-indicator">下拉刷新</div>, release : <div className="list-view-indicator">下拉刷新</div>, finish : <div></div>}}
                                />}
                                onEndReached={this.onEndReached}
                                pageSize={20}
                                initialListSize={initListViewSize}
                                onScroll={this.onScroll}
                            />
                    </Tabs>

                    <Footer ref={el => this.footer = el} active='index-active'/>
            </div>
        );
    }
}

export default Index;
